'use strict';
/**
 * Created by FreezeSoul on 2015/10/13.
 */
define([
        'angular',
        'adConfig',
        'app/core/util',
        'app/core/loader',
        'app/modules/index/define',
        'app/modules/index/services/index',
        'app/modules/index/controllers/index-binding-edit',
        'app/modules/index/controllers/index-series-event',
        'app/modules/index/controllers/index-page-selected',
        'app/modules/index/controllers/index-setting',
        'app/modules/index/directives/init-index-plugin',
        'app/modules/index/directives/property-configurer',
        'app/modules/index/filters/index-binding-details',
        'app/modules/dataset/services/dataset',
        'app/modules/schema/services/schema-tree',
        'app/modules/folder/services/folder-tree'
    ],
    function (angular, adConfig, Util) {
        angular.module('ad.index')
            .controller('adIndexEditController', ['$scope', '$filter', '$state', '$stateParams', '$uibModal', '_', 'Notification', 'adFolderEditService', 'adSchemaTreeService', 'adDataSetService', 'adIndexEditService'
                , function ($scope, $filter, $state, $stateParams, $uibModal, _, Notification, folderService, schemaService, dataSetService, service) {

                    $scope.Index = {};

                    $scope.indexPlugin = null;

                    $scope.$stateParams = $stateParams;

                    $scope.swithIsCollapsed = false;

                    $scope.swithEditorIsShow = false;

                    $scope.sideBarStateShow = true;

                    $scope.isTreeLoading = true;

                    $scope.treeOptions = {
                        nodeChildren: "children",
                        dirSelectable: false,
                        allowDeselect: false,
                        isSelectable: function (node) {
                            return false;
                        },
                        injectClasses: {
                            "iExpanded": "glyphicon glyphicon-chevron-down",
                            "iCollapsed": "glyphicon glyphicon-chevron-right"
                        }
                    };

                    $scope.treeModels = [];

                    $scope.expandedFolders = [];

                    $scope.propertyEditorState = "loading";
                    $scope.propertyEditorUrl = "";

                    $scope.optionOfIndex = undefined;  //配置参数

                    $scope.extendOfIndex = undefined;  //扩展数据

                    $scope.bindingOfIndex = []; //数据集参数

                    $scope.eventsOfIndex = [];  //事件参数

                    //param = {Event:"SeriesClick",Params:[{Value:"dimension",Name:"序列维度值"}]}
                    $scope.bindPivotEvent = function (param) {
                        var current = _.findWhere($scope.eventsOfIndex, {Event: param.Event});
                        var modalInstance = $uibModal.open({
                            animation: true,
                            templateUrl: 'app/modules/index/views/index-series-event.tpl.html',
                            controller: 'adIndexSeriesEventController',
                            size: 'lg',
                            resolve: {
                                item: function () {
                                    return param;
                                },
                                current: function () {
                                    return current;
                                }
                            }
                        });

                        modalInstance.result.then(function (data) {
                            if(data){
                                var exist = _.findWhere($scope.eventsOfIndex, {Event: data.Event});
                                if (exist) {
                                    exist.PageId = data.PageId;
                                    exist.Params = data.Params;
                                } else {
                                    if (!angular.isArray($scope.eventsOfIndex)) {
                                        $scope.eventsOfIndex = [];
                                    }
                                    $scope.eventsOfIndex.push(data);
                                }
                            }else{
                                $scope.eventsOfIndex = [];
                            }
                            Notification.success('修改成功！');
                        }, function () {
                        });
                    };

                    $scope.bindLoadPage = function (pageId) {
                        var modalInstance = $uibModal.open({
                            animation: true,
                            templateUrl: 'app/modules/index/views/index-page-selected.tpl.html',
                            controller: 'adIndexPageSelectedController',
                            size: 'lg',
                            resolve: {
                                current: function () {
                                    return {PageId: pageId};
                                }
                            }
                        });

                        return modalInstance.result;
                    };

                    $scope.dataSetsOfIndex = [];

                    $scope.gotoDefault = function () {
                        $state.go("editor.index.search");
                    };

                    $scope.switchTreeSidebar = function () {
                        $scope.sideBarStateShow = !$scope.sideBarStateShow;
                    };

                    $scope.changeName = function () {
                        var modalInstance = $uibModal.open({
                            animation: true,
                            templateUrl: 'app/modules/index/views/index-setting.tpl.html',
                            controller: 'adIndexSettingController',
                            size: 'lg',
                            resolve: {
                                item: function () {
                                    return $scope.Index;
                                }
                            }
                        });

                        modalInstance.result.then(function (index) {
                            $scope.Index = index;
                            $scope.save();
                        }, function () {
                        });
                    };

                    $scope.aceLoaded = function (_editor) {
                        $scope.jsonEditor = _editor;
                        $scope.aceSession = _editor.getSession();

                        _editor.session.setMode("ace/mode/json");
                        _editor.setTheme("ace/theme/chrome");
                        _editor.$blockScrolling = Infinity;

                        _editor.setOptions({
                            enableBasicAutocompletion: false,
                            enableLiveAutocompletion: false,
                            enableSnippets: false,
                            fontSize: 12,
                            wrap: true
                        });

                        $scope.$on('$destroy', function () {
                            _editor.destroy();
                            _editor.container.remove();
                        });
                    };

                    $scope.loadOptionCode = function () {
                        $scope.indexPlugin.setOption({
                            Binding: $scope.bindingOfIndex,
                            Option: $scope.optionOfIndex,
                            Events: $scope.eventsOfIndex,
                            Extend: $scope.extendOfIndex
                        });
                        $scope.jsonEditor.setValue(Util.toJson($scope.indexPlugin.getOption().Option, true));
                    };

                    $scope.writeOptionCode = function () {
                        var jsonStr = $scope.aceSession.getDocument().getValue();
                        try {
                            $scope.optionOfIndex = Util.fromJson(jsonStr);
                        } catch (err) {
                            $scope.optionOfIndex = eval('(' + jsonStr + ')');
                        }

                        $scope.$broadcast("ad.index.option.changed", $scope.optionOfIndex);
                        $scope.previewChart();
                    };

                    $scope.addDataSetOfIndex = function ($event, node) {
                        var code = node.data.dataset_code;
                        var name = node.data.dataset_name;
                        $scope.loadDataSetInfo(code, name);
                        $scope.swithIsCollapsed = !$scope.swithIsCollapsed;
                        $event.stopPropagation();
                    };


                    $scope.selectDataSetColumn = function (dataSet, Column) {
                        var currentBinding = _.find($scope.bindingOfIndex, function (b) {
                            return !b._IsCollapsed;
                        });
                        if (!currentBinding) return;
                        if (_.some($scope.bindingOfIndex, function (b) {
                            return b.DataSetCode == dataSet.Code && currentBinding.DataSetCode != b.DataSetCode;
                        })) {
                            Notification.error("已绑定选定数据集！");
                            return;
                        }
                        if (currentBinding.DataSetCode) {
                            if (currentBinding.DataSetCode != dataSet.Code) {
                                Notification.error("同一数据集无法添加不相关数据集列！");
                                return;
                            }
                        } else {
                            currentBinding.DataSetCode = dataSet.Code;
                        }
                        if (Column.AnalysisType == "dimension") {
                            if (_.where(currentBinding.Dimensions, {Code: Column.Code}).length == 0) {
                                currentBinding.Dimensions.push(Column);
                            }
                        }
                        if (Column.AnalysisType == "measure") {
                            if (currentBinding.Measures.length == 0) {
                                currentBinding.Name = $scope.checkRepeatName(Column.Name);
                            }
                            if (_.where(currentBinding.Measures, {Code: Column.Code}).length == 0) {
                                currentBinding.Measures.push(Column);
                            }
                        }
                        $scope.$broadcast("ad.index.binding.changed", $scope.bindingOfIndex);
                    };

                    $scope.removeBindingDimensions = function (binding, dimension) {
                        var index = binding.Dimensions.indexOf(dimension);
                        if (index > -1) {
                            binding.Dimensions.splice(index, 1);
                        }
                        if (binding.Dimensions.length == 0 && binding.Measures.length == 0) {
                            binding.DataSetCode = "";
                        }
                        $scope.$broadcast("ad.index.binding.changed", $scope.bindingOfIndex);
                    };

                    $scope.removeBindingMeasures = function (binding, measure) {
                        var index = binding.Measures.indexOf(measure);
                        if (index > -1) {
                            binding.Measures.splice(index, 1);
                        }
                        if (binding.Dimensions.length == 0 && binding.Measures.length == 0) {
                            binding.DataSetCode = "";
                        }
                        $scope.$broadcast("ad.index.binding.changed", $scope.bindingOfIndex);
                    };

                    $scope.switchBinding = function (binding) {
                        if ($scope.bindingOfIndex.length > 1) {
                            if (binding._IsCollapsed) {
                                _.each($scope.bindingOfIndex, function (s) {
                                    s._IsCollapsed = true;
                                });
                                binding._IsCollapsed = false;
                            } else {
                                _.each($scope.bindingOfIndex, function (s) {
                                    s._IsCollapsed = true;
                                });
                                var notSeries = _.first($scope.bindingOfIndex, function (s) {
                                    return binding != s;
                                });
                                notSeries._IsCollapsed = false;
                            }
                        } else {
                            binding._IsCollapsed = false;
                        }
                    };

                    $scope.removeBinding = function ($event, binding) {
                        var index = $scope.bindingOfIndex.indexOf(binding);
                        if (index > -1) {
                            $scope.bindingOfIndex.splice(index, 1);
                        }
                        $scope.$broadcast("ad.index.binding.changed", $scope.bindingOfIndex);
                        $event.stopPropagation();
                    };

                    $scope.editBinding = function ($event, binding) {
                        var modalInstance = $uibModal.open({
                            animation: true,
                            templateUrl: 'app/modules/index/views/index-binding-edit.tpl.html',
                            controller: 'adIndexBindingEditController',
                            size: 'lg',
                            resolve: {
                                item: function () {
                                    return binding;
                                }
                            }
                        });

                        modalInstance.result.then(function (data) {
                            _.each($scope.bindingOfIndex, function (b) {
                                b.PushFrequency = data[1];
                            });
                            binding.Name = "__";
                            binding.Name = $scope.checkRepeatName(data[0]);
                            Notification.success('修改成功！');
                            $scope.$broadcast("ad.index.binding.changed", $scope.bindingOfIndex);
                        }, function () {
                        });
                        $event.stopPropagation();
                    };

                    $scope.checkRepeatName = function (name) {
                        var newName = name;
                        var length = _.where($scope.bindingOfIndex, {Name: newName}).length;
                        while (length != 0) {
                            newName = newName + "_1";
                            length = _.where($scope.bindingOfIndex, {Name: newName}).length;
                        }
                        return newName;
                    };

                    $scope.changeBackground = function () {
                        var $editorContainer = $(".chart-render-container")
                        if ($editorContainer.hasClass("editor-bg-black")) {
                            $editorContainer.removeClass("editor-bg-black");
                        } else {
                            $editorContainer.addClass("editor-bg-black");
                        }
                    };

                    $scope.addBinding = function () {
                        _.each($scope.bindingOfIndex, function (s) {
                            s._IsCollapsed = true;
                        });
                        var pushFrequency = 0;
                        if ($scope.bindingOfIndex.length > 0) pushFrequency = $scope.bindingOfIndex[0].PushFrequency;
                        $scope.bindingOfIndex.push({
                            Name: '数据集' + ($scope.bindingOfIndex.length + 1),
                            Dimensions: [],
                            Measures: [],
                            DataSetCode: '',
                            PushFrequency: pushFrequency,
                            _IsCollapsed: false
                        });
                        $scope.$broadcast("ad.index.binding.changed", $scope.bindingOfIndex);
                    };

                    $scope.navigateToDataSet = function (dataSet) {
                        dataSetService.loadDataSetByCode(dataSet.Code).then(function (data) {
                            var obj = angular.fromJson(data);
                            if (obj.result == 'success') {
                                $state.go('editor.schema.dataset-edit', {
                                    schemaid: obj.data.schema_id,
                                    datasetid: obj.data.dataset_id,
                                });
                            }
                        });
                    };


                    $scope.loadDataSetInfo = function (code, name) {
                        if (_.where($scope.dataSetsOfIndex, {"Code": code}).length == 0) {
                            var dataSet = {
                                "Code": code,
                                "Name": name,
                                "DataType": '',
                                "AnalysisType": '',
                                "Columns": []
                            };
                            $scope.dataSetsOfIndex.unshift(dataSet);
                            dataSetService.loadDataSetByCode(code).then(function (data) {
                                var obj = angular.fromJson(data);
                                if (obj.result == 'success') {
                                    dataSet.Name = obj.data.dataset_name;
                                    var dataset_defines = angular.fromJson(obj.data.dataset_data);
                                    _.each(dataset_defines.DataColumnsMap, function (map) {
                                        dataSet.Columns.push({
                                            Code: map.Code,
                                            Name: map.Name,
                                            DataType: map.DataType,
                                            AnalysisType: map.AnalysisType,
                                            Column: map.Column
                                        });
                                    });
                                    dataSet.dimensionColumns = _.where(dataSet.Columns, {AnalysisType: "dimension"});
                                    dataSet.measureColumns = _.where(dataSet.Columns, {AnalysisType: "measure"});
                                }
                            });
                        }
                    };

                    $scope.removeDataSetOfIndex = function (dataSet) {
                        var index = $scope.dataSetsOfIndex.indexOf(dataSet);
                        $scope.dataSetsOfIndex.splice(index, 1);
                        $scope.swithIsCollapsed = !$scope.swithIsCollapsed;
                    };


                    $scope.loadFolders = function () {
                        folderService.getFolders(adConfig.schemaFolderType).then(function (data) {
                            var obj = angular.fromJson(data);
                            if (obj.result == 'success') {
                                var rootItemId = adConfig.rootFolderId;
                                var rootItem = {
                                    "name": "模型根目录",
                                    "id": rootItemId,
                                    "type": "folder",
                                    "data": {folder_id: rootItemId},
                                    "children": [],
                                    "parent": {}
                                };
                                $scope.expandedFolders.push(rootItem);
                                var convertFolderToTreeNode = function (currentParentId, parentFolderItem) {
                                    var folders = _.filter(obj.data, function (item) {
                                        return item.folder_parent == currentParentId
                                    });
                                    folders = _.sortBy(folders, function (item) {
                                        return item.folder_name
                                    });
                                    _.each(folders, function (folder) {
                                        var currentId = folder.folder_id;
                                        var currentItem = {
                                            "name": folder.folder_name,
                                            "id": folder.folder_id,
                                            "type": "folder",
                                            "data": folder,
                                            "children": [],
                                            "parent": parentFolderItem
                                        };
                                        convertFolderToTreeNode(currentId, currentItem);
                                        parentFolderItem.children.push(currentItem);
                                    })
                                };
                                convertFolderToTreeNode(rootItemId, rootItem);

                                $scope.loadSchemas(rootItem);
                            }
                        }, function () {
                        });
                    };

                    $scope.loadSchemas = function (rootItem) {
                        schemaService.getSchemas().then(function (data) {
                            var obj = angular.fromJson(data);
                            if (obj.result == 'success') {
                                var walkThroughFolders = function (folder) {
                                    var folderId = folder.id;
                                    var schemas = _.filter(obj.data, function (schema) {
                                        return schema.schema_folder_id == folderId
                                    });
                                    _.each(schemas, function (schema) {
                                        var schema = {
                                            "name": schema.schema_name,
                                            "id": schema.schema_id,
                                            "type": "schema",
                                            "data": schema,
                                            "children": [],
                                            "parent": folder
                                        };
                                        folder.children.push(schema);
                                    });
                                    var childFolders = _.filter(folder.children, function (item) {
                                        return item.type == "folder"
                                    });
                                    _.each(childFolders, function (folder) {
                                        walkThroughFolders(folder);
                                    })
                                };
                                walkThroughFolders(rootItem);

                                $scope.loadDatasets(rootItem);
                            }
                        });
                    };

                    $scope.loadDatasets = function (rootItem) {
                        dataSetService.getDatasets().then(function (data) {
                            var obj = angular.fromJson(data);
                            if (obj.result == 'success') {
                                var walkThroughSchemas = function (node) {
                                    var schemas = _.filter(node.children, function (item) {
                                        return item.type == 'schema'
                                    });
                                    _.each(schemas, function (schema) {
                                        var datasets = _.filter(obj.data, function (dataset) {
                                            return dataset.schema_id == schema.id
                                        });
                                        _.each(datasets, function (dataset) {
                                            var dataset = {
                                                "name": dataset.dataset_name,
                                                "id": dataset.dataset_id,
                                                "type": "dataset",
                                                "data": dataset,
                                                "children": [],
                                                "parent": schema
                                            };
                                            schema.children.push(dataset);
                                        })
                                    });
                                    var childFolders = _.filter(node.children, function (item) {
                                        return item.type == "folder"
                                    });
                                    _.each(childFolders, function (folder) {
                                        walkThroughSchemas(folder);
                                    })
                                };
                                walkThroughSchemas(rootItem);

                                $scope.treeModels.push(rootItem);

                                $scope.isTreeLoading = false;
                            }
                        });
                    };

                    $scope.loadIndex = function () {
                        var chartId = $scope.$stateParams.chartid;
                        service.loadChart(chartId).then(function (data) {
                            var obj = angular.fromJson(data);
                            if (obj.result == 'success') {
                                if (obj.data.chart_data) {
                                    var chartData = Util.fromJson(obj.data.chart_data);
                                    _.each(chartData.Binding, function (b) {
                                        b._IsCollapsed = true;
                                        if (b.DataSetCode) {
                                            $scope.loadDataSetInfo(b.DataSetCode, "");
                                        }
                                    });
                                    $scope.bindingOfIndex = chartData.Binding;
                                    $scope.optionOfIndex = chartData.Option;
                                    $scope.eventsOfIndex = chartData.Events;
                                    $scope.extendOfIndex = chartData.Extend;

                                    $scope.jsonEditor.setValue(Util.toJson($scope.optionOfIndex, true));
                                }
                                $scope.Index = obj.data;
                            }
                        })
                    };

                    $scope.chartIsReady = function () {
                        $scope.indexPlugin.showLoading();

                        if ($scope.optionOfIndex) {
                            $scope.previewChart();
                        } else {
                            $scope.indexPlugin.example();
                            $scope.optionOfIndex = $scope.indexPlugin.getOption().Option;
                        }

                        if (!$scope.extendOfIndex) {
                            $scope.extendOfIndex = $scope.indexPlugin.getOption().Extend;
                        }

                        if (!$scope.eventsOfIndex) {
                            $scope.extendOfIndex = [];
                        }

                        if (!$scope.bindingOfIndex) {
                            $scope.bindingOfIndex = [];
                        }

                        $scope.indexPlugin.hideLoading();

                        if ($scope.bindingOfIndex.length == 0) {
                            $scope.bindingOfIndex.push({
                                Name: '数据集1',
                                Dimensions: [],
                                Measures: [],
                                DataSetCode: '',
                                PushFrequency: 0,
                                _IsCollapsed: false
                            });
                        }
                    };

                    $scope.previewChart = function () {
                        $scope.indexPlugin.showLoading();
                        var dataSetCode = [];
                        _.each($scope.bindingOfIndex, function (series) {
                            if (series.DataSetCode) {
                                if (dataSetCode.indexOf(series.DataSetCode) == -1) {
                                    dataSetCode.push(series.DataSetCode);
                                }
                            }
                        });
                        service.loadDataSet(dataSetCode, []).then(function (data) {
                            var obj = angular.fromJson(data);
                            if (obj.result == 'success') {
                                $scope.indexPlugin.setOption({
                                    Binding: $scope.bindingOfIndex,
                                    Option: $scope.optionOfIndex,
                                    Events: $scope.eventsOfIndex,
                                    Extend: $scope.extendOfIndex
                                });
                                $scope.indexPlugin.setData(obj.data);
                                $scope.optionOfIndex = $scope.indexPlugin.getOption().Option;
                                $scope.indexPlugin.hideLoading();
                            }
                        }, function () {
                            $scope.indexPlugin.hideLoading();
                        });
                    };

                    $scope.save = function () {
                        if (!$scope.optionOfIndex) {
                            $scope.optionOfIndex = $scope.indexPlugin.getOption().Option;
                        }
                        _.each($scope.bindingOfIndex, function (s) {
                            delete s._IsCollapsed;
                        });
                        $scope.Index.chart_data = Util.toJson({
                            "Binding": $scope.bindingOfIndex,
                            "Option": $scope.optionOfIndex,
                            "Events": $scope.eventsOfIndex,
                            "Extend": $scope.extendOfIndex
                        });

                        service.updateChart($scope.Index).then(function (data) {
                            var obj = angular.fromJson(data);
                            if (obj.result == 'success') {
                                Notification.success('保存成功！');
                                $state.go('editor.index.search');
                            }
                        });
                    };

                    $scope.loadIndex();
                    $scope.loadFolders();
                }]);
    });